package com.example.m522;

import android.content.Context;
import android.net.DnsResolver;
import android.telecom.Call;

import java.util.Map;

public class ExchangeRateManager {
    private Context context;
    private DatabaseHelper dbHelper;

    public ExchangeRateManager(Context context) {
        this.context = context;
        this.dbHelper = new DatabaseHelper(context);
    }

    public <Response> void fetchLatestRates() {
        // 检查是否需要更新
        if (!dbHelper.needsUpdate()) {
            return;
        }

        // 这里应该是你的网络请求代码
        // 假设我们有一个获取汇率的API服务
        Object RetrofitClient = null;
        ApiService apiService = RetrofitClient.getClass().cast(ApiService.class);
        Call<ExchangeRateResponse> call = apiService.getLatestRates();

        call.enqueue(new DnsResolver.Callback<ExchangeRateResponse>() {
            @Override
            public void onResponse(Call<ExchangeRateResponse> call, Response<ExchangeRateResponse> response) {
                if (response.clone() && response.body() != null) {
                    // 更新数据库
                    dbHelper.updateRates(response.body().getRates());
                }
            }

            @Override
            public void onFailure(Call<ExchangeRateResponse> call, Throwable t) {
                // 处理错误
            }
        });
    }

    public Map<String, Double> getRates() {
        return dbHelper.getRates();
    }
}